package com.welleys.test.servlet.http.apply;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "FileDownWithServlet", urlPatterns = "/FileDownWithServlet")
public class FileDownWithServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        downfile(req,resp);
    }

    private void downfile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        final  int BYTES = 1024;

        int length = 0;

        ServletOutputStream outputStream = resp.getOutputStream();
        ServletContext context = getServletConfig().getServletContext();

        String mimetype = context.getMimeType("");
        resp.setContentType(mimetype);
        resp.setHeader("Content-Disposition", "attachment; filename=" + "filename" );

        InputStream is = context.getResourceAsStream("/file");

        byte[] buf = new byte[BYTES];
        while((null != is)&&(-1!=(length=is.read(buf)))){
            outputStream.write(buf,0,length);
        }

        outputStream.flush();
        outputStream.close();
    }
}
